<script setup lang="ts">
import {
  type DatePickType,
  ElDatePicker,
  ElForm,
  ElFormItem,
  ElInput,
  ElOption,
  ElSelect,
} from 'element-plus'
import { PERIODS } from '../types'
import SearchButton from '@/components/SearchButton/SearchButton.vue'

defineEmits<{
  (e: 'search'): void
}>()

const info = defineModel<{
  keyword: string
  period: PERIODS
  time: string | [string, string]
}>({ required: true })

const timeType = computed<DatePickType>(() => {
  const { period } = toValue(info)
  let type: DatePickType = 'daterange'
  switch (period) {
    case PERIODS.HOUR:
      type = 'datetimerange'
      break
    case PERIODS.MONTH:
      type = 'monthrange'
      break
    case PERIODS.YEAR:
      type = 'year'
      break
    default:
      type = 'daterange'
  }
  return type
})

const timeFormat = computed(() => {
  const { period } = toValue(info)
  let format = 'YYYY-MM-DD'
  switch (period) {
    case PERIODS.HOUR:
      format = 'YYYY-MM-DD HH:mm'
      break
    case PERIODS.MONTH:
      format = 'YYYY-MM'
      break
    case PERIODS.YEAR:
      format = 'YYYY'
      break
    default:
      format = 'YYYY-MM-DD'
  }
  return format
})

function changePeriod() {
  info.value.time = ['', '']
}

function disabledDateFn(date: Date) {
  return (
    new Date().getTime() - date.getTime() <= 24 * 60 * 1000
  )
}
function disabledMinutesFn() {
  return Array(60).fill(1).map((_v, i) => i + 1)
}
</script>

<template>
  <ElForm inline :model="info">
    <ElFormItem label="指标名称">
      <ElInput
        v-model="info.keyword"
        placeholder="关键字"
        clearable
      />
    </ElFormItem>
    <ElFormItem label="周期">
      <ElSelect
        v-model="info.period"
        class="free"
        style="width: 100px"
        @change="changePeriod"
      >
        <ElOption
          :value="PERIODS.HOUR"
          label="小时"
        />
        <ElOption
          :value="PERIODS.DATE"
          label="日"
        />
        <ElOption
          :value="PERIODS.MONTH"
          label="月"
        />
        <ElOption
          :value="PERIODS.YEAR"
          label="年"
        />
      </ElSelect>
    </ElFormItem>
    <ElFormItem label="时间区间">
      <ElDatePicker
        v-if="info.period === PERIODS.HOUR"
        v-model="info.time"
        type="datetimerange"
        format="YYYY-MM-DD HH:mm"
        value-format="YYYY-MM-DD HH:mm"
        :disabled-date="disabledDateFn"
        :disabled-minutes="disabledMinutesFn"
      />
      <ElDatePicker
        v-else
        v-model="info.time"
        :type="timeType"
        :format="timeFormat"
        :value-format="timeFormat"
        :disabled-date="disabledDateFn"
      />
    </ElFormItem>
    <ElFormItem>
      <SearchButton @click="$emit('search')" />
    </ElFormItem>
  </ElForm>
</template>
